package littlecyberwar.ui;

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;


import littlecyberwar.control.*;
import littlecyberwar.model.*;
import littlecyberwar.util.*;
import littlecyberwar.tool.MouseHandler;
import ModuleBuilder.UI.tree.ScenarioDetailPanel;
import javax.swing.text.Document;

public class MainFrame extends JFrame {

  JPanel contentPane;
  JMenuBar jMenuBar1 = new JMenuBar();
  JMenu onlineStatus = new JMenu();
  JMenu jMenuFile = new JMenu();
  JMenuItem jMenuFileOpen = new JMenuItem();
  JMenuItem jMenuFileSave = new JMenuItem();  
  JMenuItem jMenuFileOpenXML = new JMenuItem();
  JMenuItem jMenuFileSaveXML = new JMenuItem();  
  JMenuItem jMenuFileExit = new JMenuItem();  
  JMenuItem jMenuFileRecordMove = new JMenuItem(); 
  JMenuItem jMenuFileRecordMoveStop = new JMenuItem();  
  JMenuItem jMenuFileRecordMoveLoad = new JMenuItem();
  
  JMenu jMenuAction = new JMenu();
  JMenuItem jMenuActionPlayBackOne = new JMenuItem(); 
  JMenuItem jMenuActionMoveForward= new JMenuItem();
  JMenuItem jMenuActionPivotRight= new JMenuItem();
  JMenuItem jMenuActionPivotLeft= new JMenuItem();
  JMenuItem jMenuActionSideStep= new JMenuItem();
  JMenuItem jMenuActionBack= new JMenuItem();
  JMenuItem jMenuActionFreeForm= new JMenuItem();
  JMenuItem jMenuActionDeploy= new JMenuItem();
  JMenuItem jMenuActionOblique= new JMenuItem();
  JMenuItem jMenuActionRotate= new JMenuItem();
  JMenuItem jMenuActionDice= new JMenuItem();
  JMenuItem jMenuActionTapeMeasure= new JMenuItem();
  JMenuItem jMenuActionWatch= new JMenuItem();
  JMenuItem jMenuActionChat= new JMenuItem();
  JMenuItem jMenuActionAlignFacing= new JMenuItem();
  JMenuItem jMenuActionAlignVertical= new JMenuItem();
  JMenuItem jMenuActionAlignHorizontal= new JMenuItem();
  JMenuItem jMenuActionRemove= new JMenuItem();
  JMenuItem jMenuActionChangeLayer= new JMenuItem();
  JMenuItem jMenuActionReset = new JMenuItem();
   
  JMenu jMenuHelp = new JMenu();
  JMenuItem jMenuScenarioDetails = new JMenuItem();
  JMenuItem jMenuHelpAbout = new JMenuItem();
  
  // Tray related stuff
  JMenu jMenuTray = new JMenu();
	static HashMap allTrays = new HashMap(3);	

  JToolBar jToolBar = new JToolBar();
  JButton jButton1 = new JButton();
  JButton jButton2 = new JButton();
  JButton jButton3 = new JButton();
  ImageIcon image1;
  ImageIcon image2;
  ImageIcon image3;
  JLabel statusBar = new JLabel();

  BorderLayout borderLayout1 = new BorderLayout();
  private static int trayIdSeed=1;
	Tray trayAFrame = new Tray("Tray A", new Integer(10));
//  Tray trayBFrame = new Tray("Tray B", new Integer(20));

  PlayingBoardModel model;
  

  	final JFileChooser fc = new JFileChooser();
  	private ModelChangeFacade modFacade;
  
	private FileCmdBackingStore fb;
	private FileCmdHandler fcHandler;
	
	private ChatPanel chatPanel;
	//private DieRollDialog dieRollTool;
	public PlayingBoardPanel pbp;
	private MiniMapPanel mmp;
	JScrollPane scrollMap;
	private ControlPanel controlP;
	
	static HashMap trayLookup= new HashMap(2);
	private InternalCmdFacade icmd;
	private static MainFrame instance;
	
	/**Construct the frame*/
  public MainFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
	// this.addWindowFocusListener(this);

	// put globally useful things into the Util dictionary
	Util.setStatusBar( statusBar );

	// !!stick in a new PLayingBoardPanel
    model = new PlayingBoardModel();
    Util.lookup.put(Util._PLAYING_BOARD_MODEL, model);
    Util.lookup.put(Util._MAIN_FRAME, this);
	modFacade = new ModelChangeFacade( model );

	// modFacade.addBackingStore(new FileCmdBackingStore());
    Util.lookup.put(Util._MODEL_FACADE, modFacade);
    
	// setup the main game Frame
	contentPane = (JPanel) this.getContentPane();
	contentPane.setLayout(borderLayout1);
	this.setSize(new Dimension(800, 600));
	this.setTitle("Little Cyber War");    
	statusBar.setText(" ");
	
	// The Chat Panel is added to the bottom
	chatPanel = new ChatPanel(statusBar);
	contentPane.add(chatPanel, BorderLayout.SOUTH);
	modFacade.setChatPanel(chatPanel);
	
	pbp = new PlayingBoardPanel();
    pbp.setModel( model );
	pbp.setChatOutput(chatPanel);
	pbp.setStatusOutput(statusBar);
	
	modFacade.setBoardPanel(pbp);

	// setup minimap
	mmp = new MiniMapPanel();
	mmp.setModel( model );

	scrollMap = new JScrollPane(pbp);

	controlP = new ControlPanel(pbp);
	controlP.addMiniMapPanel(mmp);
	contentPane.add(controlP, BorderLayout.EAST);	

	// setup internal command queue for chatPanel
	icmd = pbp.getInternalCmdFacade();
	chatPanel.setInternalCmdFacade( icmd );
    	
	try {
	  jbInit();
	}
	catch(Exception e) {
	  e.printStackTrace();
	}
	controlP.associateActionsToButtons();
	
    pbp.setAutoscrolls(true);
    
	// setup another "left side" panel that contains the PlayingBoardPanel on top, 
	// and a chatPanel on the bottom
	JPanel leftPanel = new JPanel(new BorderLayout());
	leftPanel.add( scrollMap, BorderLayout.CENTER );
	leftPanel.add( chatPanel, BorderLayout.SOUTH );
	contentPane.add(leftPanel, BorderLayout.CENTER); 
	
	// setup the frame icon
	ImageIcon ic = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("LCWFrameIconYELLOW.gif"));
	Image icon = ic.getImage();
	this.setIconImage(icon);

	
	// setup scenarioManager
	ScenarioManager.setMainFrame( this );
	
	// now put up a dialog box to ask the user what kind of game he wants
	
	instance = this;
  }
  
  public static MainFrame getInstance() {
  	return ( instance );
  }

  /**Component initialization*/
  private void jbInit() throws Exception  {
	
    image1 = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("openFile.gif"));
    image2 = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("closeFile.gif"));
    image3 = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("help.gif"));

	initAction();
	initMenuItems();
 
    //! Setup the map scale factor
    double mapScale = 40;   // 40 pixels = 1 inch
    String mapDistanceUnit = "inch";
    Util.setMapScale( mapScale );
    Util.setMapDistanceUnit( mapDistanceUnit );
  }

	private void initAction() {
		jMenuFile.setText("File");
		
		jMenuFileOpen.setText("Open");
		jMenuFileOpen.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
			jMenuFileOpen_actionPerformed(e);
		  }
		});

		jMenuFileSave.setText("Save");
		jMenuFileSave.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
			jMenuFileSave_actionPerformed(e);
		  }
		});

		jMenuFileOpenXML.setText("Open XML");
		jMenuFileOpenXML.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
			jMenuFileOpenXML_actionPerformed(e);
		  }
		});

		jMenuFileSaveXML.setText("Save XML");
		jMenuFileSaveXML.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
			jMenuFileSaveXML_actionPerformed(e);
		  }
		});

		jMenuFileExit.setText("Exit");
		jMenuFileExit.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
		    jMenuFileExit_actionPerformed(e);
		  }
		});
		
		// setup record moved action
		ImageIcon recordImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("record.gif"));
		KeyStroke k = KeyStroke.getKeyStroke('r');
		LCWAction action = new RecordAction("Record", recordImage,
					 "Begin Recording Moves<r>",
					 k, this);
		jMenuFileRecordMove.setAction(action);
		Util.lookup.put(Util._recordKey, action);
		//jMenuFileRecordMove.setIcon(null);		 
	
		// Stop recorded move
		recordImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("stop.gif"));
		k = KeyStroke.getKeyStroke('k');
		action = new StopAction("Stop<k>", recordImage,
					 "Stop Recording Moves.",
					 k, this);
		jMenuFileRecordMoveStop.setAction(action);
		Util.lookup.put(Util._stopKey, action);
		//jMenuFileRecordMove.setIcon(null);		 
	
		// load recorded move
		recordImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("load.gif"));
		k = KeyStroke.getKeyStroke('l');
		action = new LoadAction("Load", recordImage,
					 "Load Recording Moves<l>",
					 k, this);
		jMenuFileRecordMoveLoad.setAction(action);
		Util.lookup.put(Util._loadKey, action);
		
		jMenuAction.setText("Action");
	
		// Playback one recorded move
		recordImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("play.gif"));
		k = KeyStroke.getKeyStroke('p');
		action = new PlayAction("Play", recordImage,
					 "Play Back One Command<p>",
					 k, this);
		jMenuActionPlayBackOne.setAction(action);
		Util.lookup.put(Util._playKey, action);
	
		jMenuHelp.setText("Help");
		
		jMenuScenarioDetails.setText("Scenario Details");
		jMenuScenarioDetails.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
		  	jMenuScenarioDetails_actionPerformed(e);
		  }
		});		
		jMenuHelpAbout.setText("About");
		jMenuHelpAbout.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
		    jMenuHelpAbout_actionPerformed(e);
		  }
		});
		
		/**
		 * Now initialize all the mode Actions
		 */
		// Watch action
		ImageIcon watchImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("watch.gif"));
		k = KeyStroke.getKeyStroke('h');
		action = new ModeAction("watch", watchImage,
					 "Watch opponent action<h>",
					 k, this, pbp, "MouseWatchHandler");
		jMenuActionWatch.setAction(action);
		Util.lookup.put(Util._watchKey, action);

		// pivot left action
		ImageIcon leftTurnImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("PivotLeft.gif"));
		k = KeyStroke.getKeyStroke('q');
		action = new ModeAction("Left<q>", leftTurnImage,
					 "wheel left",
					 k, this, pbp, "MouseRotateLeftHandler");
		jMenuActionPivotLeft.setAction(action);
		Util.lookup.put(Util._leftKey, action);

		// Move straight ahead
		ImageIcon forwardImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("ForwardArrow2.gif"));
		k = KeyStroke.getKeyStroke('w');
		action = new ModeAction("Forward", forwardImage,
					 "Move Straight Forward<w>",
					 k, this, pbp, "MouseStraightForwardHandler");
		jMenuActionMoveForward.setAction(action);
		Util.lookup.put(Util._forwardKey, action);
		
		// pivot right		
		ImageIcon rightTurnImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("PivotRight.gif"));
		k = KeyStroke.getKeyStroke('e');
		action = new ModeAction("Right", rightTurnImage,
					 "wheel right<e>",
					 k, this, pbp, "MouseRotateRightHandler");
		jMenuActionPivotRight.setAction(action);
		Util.lookup.put(Util._rightKey, action);
		
		// move backward
		ImageIcon backwardImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("BackArrow.gif"));
		k = KeyStroke.getKeyStroke('s');
		action = new ModeAction("Retrograde", backwardImage,
					 "Move Straight Back<s>",
					 k, this, pbp, "MouseBackwardHandler");
		jMenuActionBack.setAction(action);
		Util.lookup.put(Util._backKey, action);
		
		// side step
		ImageIcon sidestepImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("SideStep.gif"));
		k = KeyStroke.getKeyStroke('a');
		action = new ModeAction("Side Step", sidestepImage,
					 "Move To the Side<a>",
					 k, this, pbp, "MouseSidestepHandler");
		jMenuActionSideStep.setAction(action);
		Util.lookup.put(Util._sideKey, action);
		
		// Oblique Move
		ImageIcon obliqueMoveImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("obliqueMove.gif"));
		k = KeyStroke.getKeyStroke('o');
		action = new ModeAction("Oblique", obliqueMoveImage,
					 "Move forward within 45\"<o>",
					 k, this, pbp, "MouseObliqueHandler");
		jMenuActionOblique.setAction(action);
		Util.lookup.put(Util._obliqueKey, action);
		
		// Free form movement
		ImageIcon freeFormMoveImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("FreeForm.gif"));
		k = KeyStroke.getKeyStroke('f');
		action = new ModeAction("Freeform", freeFormMoveImage,
					 "Freeform movement<f>",
					 k, this, pbp, "MouseFreeFormHandler");
		jMenuActionFreeForm.setAction(action);
		Util.lookup.put(Util._freeKey, action);
		
		// Rotate center
		ImageIcon rotateCenterImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("rotate.gif"));		
		k = KeyStroke.getKeyStroke('c');
		action = new ModeAction("Rotate", rotateCenterImage,
					 "Rotate<c>",
					 k, this, pbp, "MouseRotateCenterHandler");
		jMenuActionRotate.setAction(action);
		Util.lookup.put(Util._rotateKey, action);
		
		// Deploy
		ImageIcon placeImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("deploy.gif"));
		k = KeyStroke.getKeyStroke('d');
		action = new ModeAction("Deploy", placeImage,
					 "Deploy Unit from Tray<d>",
					 k, this, pbp, "MousePlacementHandler");
		jMenuActionDeploy.setAction(action);
		Util.lookup.put(Util._deployKey, action);
		
		// Tape Measure
		ImageIcon rulerImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("ruler.gif"));
		k = KeyStroke.getKeyStroke('t');
		action = new ModeAction("Ruler", rulerImage,
					 "Tape Measure<t>",
					 k, this, pbp, "MouseRulerHandler");
		jMenuActionTapeMeasure.setAction(action);
		Util.lookup.put(Util._tapeKey, action);
		
		// Dice 
		ImageIcon diceImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("Dice.gif"));
		k = KeyStroke.getKeyStroke('z');
		action = new DiceAction("Dice", diceImage,
					 "Roll Dice<z>",
					 k, this);
		jMenuActionDice.setAction(action);	
		Util.lookup.put(Util._diceKey, action);
		
		// Chat
		ImageIcon chatImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("chat.gif"));
		k = KeyStroke.getKeyStroke('\n');
		action = new ChatAction("Chat", chatImage,
					 "Enter message",
					 k, this);
		jMenuActionChat.setAction(action);	
		Util.lookup.put(Util._chatKey, action);
		
		// Align facing
//		ImageIcon alignFacingImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("watch.gif"));
//		action = new ModeAction("Align Facing", alignFacingImage,
//					 "Align Facing",
//					 null, this, pbp, "MouseAlignFacingHandler");
//		jMenuActionAlignFacing.setAction(action);	
//		Util.lookup.put(Util._alignFacingKey, action);

		// Align Vertical
		ImageIcon alignVerticalImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("VerticalAlign.gif"));
		k = KeyStroke.getKeyStroke('y');
		action = new ModeAction("Align Vertical", alignVerticalImage,
					 "Align Selected Units Vertically<y>",
					 k, this, pbp, "MouseAlignVerticalHandler");
		jMenuActionAlignVertical.setAction(action);	
		Util.lookup.put(Util._alignVerticalKey, action);

		// Align Horizontal
		ImageIcon alignHorizontalImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("horizontalAlign.gif"));
		k = KeyStroke.getKeyStroke('x');
		action = new ModeAction("Align Horizontal", alignHorizontalImage,
					 "Align Selected Units Horizontally<x>",
					 k, this, pbp, "MouseAlignHorizontalHandler");
		jMenuActionAlignHorizontal.setAction(action);	
		Util.lookup.put(Util._alignHorizontalKey, action);

		// Remove
		ImageIcon removeImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("remove.gif"));
		k = KeyStroke.getKeyStroke('v');
		action = new RemoveAction("Remove", removeImage,
					 "Remove Unit(s) to Tray<v>",
					 k, this, pbp, "MouseRemoveHandler");
		jMenuActionRemove.setAction(action);	
		Util.lookup.put(Util._removeKey, action);

		// Change Layer
		ImageIcon changeLayerImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("layerChange.gif"));
		k = KeyStroke.getKeyStroke('l');
		action = new ChangeLayerAction("Change Layer", changeLayerImage,
					 "Move Unit(s) to a different layer<l>",
					 k, this, pbp, "ChangeLayerHandler");
		jMenuActionChangeLayer.setAction(action);	
		Util.lookup.put(Util._changeLayerKey, action);

		// Reset Move Distance
		ImageIcon resetMoveImage = new ImageIcon(littlecyberwar.ui.MainFrame.class.getResource("resetMovement.gif"));
		k = KeyStroke.getKeyStroke('m');
		action = new ResetMoveAction("Reset", resetMoveImage,
					 "Reset Distance Moved<m>",
					 k, this);
		jMenuActionReset.setAction(action);	
		Util.lookup.put(Util._resetMoveKey, action);
	}
  
	/**
	 * Initialize the menu
	 * @throws Exception
	 */
	private void initMenuItems(){
	  // setup tray A
	   jMenuTray.setText("Trays");
	   
	   // Initialize the Menu Bar
	   //
	   jMenuFile.add(jMenuFileOpen);	   
	   jMenuFile.add(jMenuFileSave);
	   jMenuFile.add(jMenuFileOpenXML);	   
	   jMenuFile.add(jMenuFileSaveXML);
	   jMenuFile.add(jMenuFileExit);
	   jMenuFile.addSeparator();
	   jMenuFile.add(jMenuFileRecordMove);
	   jMenuFile.add(jMenuFileRecordMoveStop);
	   jMenuFile.add(jMenuFileRecordMoveLoad);
		
	   jMenuAction.add(jMenuActionPlayBackOne);
	   jMenuAction.addSeparator();
	   jMenuAction.add(jMenuActionMoveForward);
	   jMenuAction.add(jMenuActionPivotRight);
	   jMenuAction.add(jMenuActionPivotLeft);
	   jMenuAction.add(jMenuActionSideStep);
	   jMenuAction.add(jMenuActionBack);
	   jMenuAction.add(jMenuActionFreeForm);
	   jMenuAction.add(jMenuActionDeploy);
	   jMenuAction.add(jMenuActionOblique);
	   jMenuAction.add(jMenuActionRotate);
	   jMenuAction.add(jMenuActionAlignFacing);
	   jMenuAction.add(jMenuActionAlignVertical);
	   jMenuAction.add(jMenuActionAlignHorizontal);
	   jMenuAction.add(jMenuActionRemove);
	   jMenuAction.add(jMenuActionChangeLayer);
	   jMenuAction.add(jMenuActionReset);
	   jMenuAction.addSeparator();
	   jMenuAction.add(jMenuActionDice);
	   jMenuAction.add(jMenuActionTapeMeasure);
		
	   jMenuHelp.add(jMenuScenarioDetails);
	   jMenuHelp.add(jMenuHelpAbout);
	
		// now setup the menu bar
		jMenuBar1.setLayout(new BoxLayout(jMenuBar1, BoxLayout.X_AXIS));
		jMenuBar1.add(jMenuFile);
		jMenuBar1.add(jMenuAction);
		jMenuBar1.add(jMenuTray);
		jMenuBar1.add(ViewScaleControl.getInstance());
		jMenuBar1.add(LayerControl.getInstance());
		jMenuBar1.add(jMenuHelp);		
		
		jMenuBar1.add(Box.createHorizontalGlue());
		onlineStatus.setText("Offline");
		jMenuBar1.add(onlineStatus);
		this.setJMenuBar(jMenuBar1);		   
	}	  

	// called by the scenario manager when a new tray has been added
	// 
	public void addNewTray( String name, littlecyberwar.model.TrayModel trayMod) {
		JMenuItem menuItem = new JMenuItem();
		Integer id = new Integer(trayIdSeed++);
		Tray currTray = new Tray(name,id );
		currTray.setModel(trayMod);
		trayLookup.put(menuItem, currTray);
		menuItem.setText(name);
		menuItem.addActionListener(new ActionListener()  {
		  public void actionPerformed(ActionEvent e) {
			jMenuTray_actionPerformed(e);
		  }
		});
		jMenuTray.add(menuItem);
		allTrays.put(name, trayMod);
	}
	
  /**File | Exit action performed*/
  public void jMenuFileExit_actionPerformed(ActionEvent e) {
  	if ( fb != null ){
		fb.close();
	}
  	
    System.exit(0);
  }
  
  public void jMenuFileOpen_actionPerformed(ActionEvent e) {
  	Loader.load(this);
  }
  
  public void jMenuFileSave_actionPerformed(ActionEvent e) {
  	Storer.storeScenarioModel(this);
  }

  public void jMenuFileOpenXML_actionPerformed(ActionEvent e) {
  	Loader.loadXML(this);
  }
  
  public void jMenuFileSaveXML_actionPerformed(ActionEvent e) {
  	Storer.storeScenarioModelXML(this);
  }

  /**
   * When the user wants to start to begin recording and specify the file
   * This action will:
   * 1. Open a file chooser dialog
   * 2. get a open a file back store
   * 3. set backing store to the ModelFacade
   * @param e
   */

  
  /**Help | About action performed*/
  public void jMenuHelpAbout_actionPerformed(ActionEvent e) {
    MainFrame_AboutBox dlg = new MainFrame_AboutBox(this);
    Dimension dlgSize = dlg.getPreferredSize();
    Dimension frmSize = getSize();
    Point loc = getLocation();
    dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
    dlg.setModal(true);
    dlg.show();
  }

  /**
   * Scenario Detail action performed
   * @author Milton  Soong
   *
   */
  public void jMenuScenarioDetails_actionPerformed(ActionEvent e) {
  	ScenarioDetailsDialog dlg = new ScenarioDetailsDialog();
    Dimension dlgSize = dlg.getPreferredSize();
    Dimension frmSize = getSize();
    Point loc = getLocation();
    dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
    dlg.setModal(true);
    dlg.show();
  }
  
//  public void jMenuTray_actionPerformed(Tray currTray, ActionEvent e) {
public void jMenuTray_actionPerformed(ActionEvent e) {
	JMenuItem currMenuItem = (JMenuItem)e.getSource();
	Tray currTray= (Tray)trayLookup.get(currMenuItem);
    Dimension dlgSize = currTray.getPreferredSize();
    Dimension frmSize = getSize();
    Point loc = getLocation();
    currTray.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
    currTray.show();
  }

  public void TEST_jMenuTray_actionPerformed(Tray currTray, ActionEvent e) {
	  Dimension dlgSize = currTray.getPreferredSize();
	  Dimension frmSize = getSize();
	  Point loc = getLocation();
	  currTray.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
	  currTray.show();
	}
  

  /**Overridden so we can exit when window is closed*/
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      jMenuFileExit_actionPerformed(null);
    }
  }
  
  /**
   * 
   * @author Milton  Soong
   *
   * Start the section on all the action objects 
   */
  public class RecordAction extends LCWAction {
		  public RecordAction(String text, ImageIcon icon,
							String desc, KeyStroke k, JFrame fr) {
			  super(text, icon, desc, k, fr);
		  }
	
		/**
		  * When the user wants to start to begin recording and specify the file
		  * This action will:
		  * 1. Open a file chooser dialog
		  * 2. get a open a file back store
		  * 3. set backing store to the ModelFacade
		  * @param e
		  */	
		public void actionPerformed(ActionEvent e) {
			int returnVal = fc.showSaveDialog(frame);
	
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				//This is where a real application would open the file.
				Debug.out("Saving: " + file.getName());
				fb = new FileCmdBackingStore(file);
				modFacade.addBackingStore(fb);
			} else {
				Debug.out("Open command cancelled by user.");
			}		
		}
  }

  public class StopAction extends LCWAction {
	public StopAction(String text, ImageIcon icon,
					  String desc, KeyStroke k, JFrame fr) {
		super(text, icon, desc, k, fr);
	}
	public void actionPerformed(ActionEvent e) {
		if ( fb != null) {
			fb.close();
			modFacade.deleteBackingStore(fb);
		} else {
			JOptionPane.showMessageDialog(frame, "You can not stop recording your moves because you did not start recording your moves.");
		}
	}	
  }
  
  public class LoadAction extends LCWAction {
	public LoadAction(String text, ImageIcon icon,
					  String desc, KeyStroke k, JFrame fr) {
		super(text, icon, desc, k, fr);
	}
	public void actionPerformed(ActionEvent e) {
		int returnVal = fc.showOpenDialog(frame);
	
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			//This is where a real application would open the file.
			Debug.out("Opening: " + file.getName());
			fcHandler = new FileCmdHandler(file, modFacade);
		
		} else {
			Debug.out("Open command cancelled by user.");
		}
	}
  }
  
  public class PlayAction extends LCWAction {
	public PlayAction(String text, ImageIcon icon,
					  String desc, KeyStroke k, JFrame fr) {
		super(text, icon, desc, k, fr);
	}
	public void actionPerformed(ActionEvent e) {
		if (fcHandler!= null) {
			int stat = fcHandler.processOneCmd();
			if (stat == 1) {
				// file process complete
				fcHandler.close();
				JOptionPane.showMessageDialog(frame, "Load recorded moves from file complete.");
			}
		}
	}
  }

  public class ChatAction extends LCWAction {
	public ChatAction(String text, ImageIcon icon,
					  String desc, KeyStroke k, JFrame fr) {
		super(text, icon, desc, k, fr);
	}
	public void actionPerformed(ActionEvent e) {
		chatPanel.chatInput.requestFocusInWindow();
	}
  }


	/**
	 * @return
	 */
	public PlayingBoardPanel getPbp() {
		return pbp;
	}
	
	public MiniMapPanel getMmp() {
		return ( mmp );
	}

	/**
	 * @return
	 */
	public JScrollPane getScrollMap() {
		return scrollMap;
	}

	/**
	 * @return
	 */
	public ModelChangeFacade getModFacade() {
		return modFacade;
	}

	public ProfileCardPanel getProfilePanel() {
		return(controlP.getProfilePanel());
	}
	
	public CardLayout getProfilePanelCard() {
		return(controlP.getProfilePanelCard());
	}
	/**
	 * @return
	 */
	public InternalCmdFacade getIcmd() {
		return icmd;
	}

/**
 * @return
 */
public String getOnlineStatus() {
	return (onlineStatus.getText());
}

/**
 * @param string
 */
public void setOnlineStatus(String string) {
	onlineStatus.setText(string);
}

/**
 * Following two method used by focus listener
 * (Doesn't work)
 */
public void windowGainedFocus(WindowEvent e) {

	// loop through all the trays, and toFront()
	Set allTrays = trayLookup.entrySet();
	for ( Iterator it= allTrays.iterator(); it.hasNext(); ){
		Map.Entry en = (Map.Entry)it.next();
		Tray currTray = (Tray)en.getValue();
		currTray.toFront();
	}
	return;
}

public void windowLostFocus(WindowEvent e) {
}

/**
 * 
 * @return a hashMap of all trays, where the key is the name of the Tray, and the val is the Tray Object
 */
public static HashMap getAllTrays() {
	return ( allTrays );
}

	/**
	 * @return Returns the controlP.
	 */
	public ControlPanel getControlP() {
		return controlP;
	}
}

class ScenarioDetailsDialog extends JDialog {
	
	  static Dimension size;
	  
	  static {
	  	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();	
		int h = (int)(screenSize.height * .5);
		int w = (int)(screenSize.width * .4);
		size = new Dimension(w,h);
	  }
	
		/* (non-Javadoc)
	 * @see java.awt.Component#getPreferredSize()
	 */
	public  Dimension getPreferredSize() {
		return ( size );
	}
    
    public ScenarioDetailsDialog() {
		this.setTitle("Scenario Details");
		ScenarioDetailPanel detailPanel = new ScenarioDetailPanel();
		
		// fill in the scenario detail info
		String scenarioName = littlecyberwar.util.Util.getScenarioName();
		String distanceUnit = littlecyberwar.util.Util.getMapDistanceUnit();
		double scale = littlecyberwar.util.Util.getMapScale();
		Document doc = littlecyberwar.util.Util.getScenarioNotes();
		
		detailPanel.setDistanceUnitTextField(distanceUnit);
		detailPanel.setNameTextField(scenarioName);
		detailPanel.setMapScaleTextField(String.valueOf(scale));
		detailPanel.setNotesArea(doc);
		
		detailPanel.disableEditable();
		
		JPanel diagPanel = new JPanel();
		diagPanel.setLayout(new BorderLayout());
		diagPanel.add(detailPanel, BorderLayout.CENTER);
		JButton ok = new JButton("OK");
		diagPanel.add(ok, BorderLayout.SOUTH);
		this.setContentPane(diagPanel);
		this.pack();
		
		// Ok click of the button, whack the dialog
		ok.addActionListener(new ActionListener()  {
			  public void actionPerformed(ActionEvent e) {
			  	dispose();
			  }
		});
	}
}